#!/usr/bin/env ruby
# Vendors the MIME type config from the mime-db list
# usage: script/vendor-mimes

require "json"
require "open-uri"

config = File.expand_path "../lib/bridgetown-core/mime.types", __dir__

# Create an array of vendored mimetype => [extensions]
mimes = {}
json = open("https://raw.githubusercontent.com/jshttp/mime-db/master/db.json").read
data = JSON.parse(json)
data.reject! { |mime, meta| meta["extensions"].nil? || meta["extensions"].empty? }
data.each do |mime, meta|
  # Normalize extensions and mime-types
  mime = mime.downcase.strip
  extensions = meta["extensions"].map { |e| e.downcase.strip }.compact

  # If a given extension is listed multiple times, prefer the first one listed
  extensions.reject! { |extension| mimes.values.flatten.include?(extension) }

  next if extensions.empty?
  mimes[mime] = [] if mimes[mime].nil?
  mimes[mime].concat extensions
end

strlen = mimes.keys.max_by(&:length).length
output = ""
output << "# Woah there. Do not edit this file directly.\n"
output << "# This file is generated automatically by script/vendor-mimes.\n\n"
mimes = mimes.sort_by { |k,v| k }
output << mimes.map { |mime,extensions| "#{mime.ljust(strlen)} #{extensions.join(" ")}" }.join("\n")

File.write(config, output)
